package com.swak.frame.ratelimit;

import java.lang.reflect.Method;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ClassUtils;

import com.swak.frame.filter.annotation.SwakMethod;
import com.swak.frame.ratelimit.annotation.RateLimit;

public class RateLimitCodeUtil {
    private static final String PREFIX = "ratelimit";

    public static String getlimtResource(RateLimit rateLimit, Method method, Class<?> targetClass) {
        String limitCode = rateLimit.key();
        if (StringUtils.isEmpty(limitCode)) {
            String className = ClassUtils.getUserClass(targetClass).getSimpleName();
            String methodName = method.getName();
            limitCode = String.format("%s_%s_%s", PREFIX, className, methodName);
        }
        return limitCode;
    }

    public static String getlimtResource(SwakMethod swakMethod, Method method,
        Class<?> targetClass) {
        if (ArrayUtils.isEmpty(swakMethod.rateLimit())) {
            return null;
        }

        RateLimit rateLimit = swakMethod.rateLimit()[0];
        return getlimtResource(rateLimit, method, targetClass);
    }

}
